import { Service } from 'egg';
import { SHA256 } from 'crypto-js';
/**
 * WeCode Service
 */
export default class WeCode extends Service {

  /**
   * 获取华为云AccessToken
   */
  public async getAccessToken() {
    const { ctx } = this;
    try {
      const url = 'https://open.welink.huaweicloud.com/api/auth/v2/tickets';
      const { data } = await ctx.curl(url, {
        method: 'POST',
        headers: {
          'content-type': 'application/json',
        },
        data: {
          client_id: this.config.appId,
          client_secret: this.config.appKey,
        },
        dataType: 'json',
      });
      console.log('获取华为云AccessToken', data);

      if (data.code === '0') {
        return data;
      }
      throw new Error('获取华为云AccessToken错误');
    } catch (e) {
      throw e;
    }
  }

  /**
   * 获取jsApi票据
   * @param token AccessToken
   */
  public async getJsApiTicket(token) {
    const { ctx } = this;
    try {
      const url = 'https://open.welink.huaweicloud.com/api/auth/v1/jstickets';
      const { data } = await ctx.curl(url, {
        method: 'GET',
        headers: {
          'content-type': 'application/json',
          'x-wlk-Authorization': token,
        },
        data: {
          client_id: this.config.appId,
          client_secret: this.config.appKey,
        },
        dataType: 'json',
      });
      console.log('获取华为云jsApiTicket', data);
      if (data.code === '0') {
        return data;
      }
      throw new Error('获取华为云jsApiTicket错误');
    } catch (e) {
      throw e;
    }
  }

  /**
   * 签名
   * @param jsTicket 票据
   * @param nonceStr 随机码 如2020-02-14
   * @param timeStamp 时间戳 1562132124
   * @param url 签名页面路径 http://baidu.com
   */
  public async sign(jsTicket, nonceStr, timeStamp, url) {
    const urldecode = decodeURI(url);
    const plain = 'jsapi_ticket=' + jsTicket + '&noncestr=' + nonceStr + '&timestamp=' + timeStamp
        + '&url=' + urldecode;
    return SHA256(plain).toString();
  }

  /**
   * 根据免登陆授权码code获取用户id和租户id
   * @param token AccessToken
   * @param code 免登陆授权码
   */
  public async getUserIdByCode(token: string, code: string) {
    const { ctx } = this;
    try {
      const url = 'https://open.welink.huaweicloud.com/api/auth/v2/userid';
      const { data } = await ctx.curl(url, {
        method: 'GET',
        headers: {
          'content-type': 'application/json',
          'x-wlk-Authorization': token,
        },
        data: {
          code,
        },
        dataType: 'json',
      });
      console.log('根据免登陆授权码code获取用户在华为云的id', data);
      if (data.code === '0') {
        return data;
      }
      throw new Error('根据免登陆授权码code获取用户在华为云的id错误');
    } catch (e) {
      throw e;
    }
  }

  /**
   * 根据userId,mobileNumber,corpUserId三者其一获取用户信息
   * @param token access_token
   * @param userId 用户帐号
   * @param mobileNumber 绑定的手机号码
   * @param corpUserId 该用户在租户自身系统的登录标识，用于认证和邮箱登录（客户内唯一）
   */
  public async getUserInfo(token: string, userId?: string, mobileNumber?: string, corpUserId?: string) {
    const { ctx } = this;
    if (!userId && !mobileNumber && !corpUserId) {
      throw new Error('请传入userId,mobileNumber,corpUserId三者其一获取用户信息');
    }
    try {
      const url = 'https://open.welink.huaweicloud.com/api/contact/v1/users';
      const { data } = await ctx.curl(url, {
        method: 'GET',
        headers: {
          'content-type': 'application/json',
          'x-wlk-Authorization': token,
        },
        data: {
          userId,
          mobileNumber,
          corpUserId,
        },
        dataType: 'json',
      });
      console.log('获取华为云用户信息', data);
      if (data.code === '0') {
        return data;
      }
      throw new Error('获取华为云用户信息错误');
    } catch (e) {
      throw e;
    }
  }
}
